package com.ysh.dao.impl;

import com.ysh.dao.ItemDao;
import com.ysh.dao.UserDao;
import com.ysh.domain.Item;
import com.ysh.domain.User;
import com.ysh.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
    dao 持久层实现类

 */
public class ItemDaoImpl implements ItemDao {
    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;
    private String sql = null;
    /*
        添加商品信息
     */
    @Override
    public int addItem(Item item) {
        // 定义返回值
        int result = 0;
        try {
            // 获取连接
            conn = JDBCUtils.getConnection();
            // 创建SQL语句
            sql = "insert into items values(?,?,?,?)";
            // 预编译，获取操作对象
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            pstmt.setString(1,item.getId());
            pstmt.setString(2,item.getIname());
            pstmt.setDouble(3,item.getPrice());
            pstmt.setString(4,item.getAddress());
            // 4. 执行sql语句，获取结果集
            System.out.println(sql);
            result = pstmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            // 释放资源
            JDBCUtils.close(conn,pstmt);
        }
        // 返回结果
        return result;
    }

    /*
        查询商品信息
     */
    @Override
    public List<Item> findItems() {
        Item item = null;
        List<Item> list = new ArrayList<>();
        try {
            // 获取连接
            conn = JDBCUtils.getConnection();
            // 创建SQL语句
            sql = "select * from items";
            // 预编译，获取操作对象
            pstmt = conn.prepareStatement(sql);
            // 4. 执行sql语句，获取结果集
            rs = pstmt.executeQuery();
            // 获取结果集
            while(rs.next()){
                item = new Item(
                        rs.getString("id"),
                        rs.getString("iname"),
                        rs.getDouble("price"),
                        rs.getString("address")
                );
                list.add(item);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.close(conn, pstmt,rs);
        }
        // 返回集合
        return list;
    }

}
